 var mainIntervalId;
function load(){
    canvas = document.getElementById('mainCanvas');
    context = canvas.getContext('2d');
    spaceCanvas = document.getElementById('spaceCanvas');
    spaceContext = spaceCanvas.getContext('2d');
    leftMargin=235;
    topMargin=60;
    score=0;
    grid=new Grid(leftMargin,topMargin);
    grid.load();
    drawScore();
    return true;
   
}

function update(){
    if(grid.isEnded === 0){
        return grid.update();
    }else{
        clearInterval(mainIntervalId);
        explodeShip();
        return false;
    }
}

function startGame(){
    startCanvas = document.getElementById('startCanvas');
    contextCanvas = startCanvas.getContext('2d');
    var imgStart = new Image();
    imgStart.onload = function() {
        contextCanvas.drawImage(imgStart,450, 200, 300, 300 );
    };
    imgStart.src = 'Images/start.jpg'; 
    startCanvas.addEventListener("click", on_canvas_click, false);
   
}


function on_canvas_click() {
    contextCanvas.clearRect(0, 0, startCanvas.width, startCanvas.height);
    if(load()){
        mainIntervalId = setInterval(update,70);                     
    }
}


function explodeShip(){
    var expSound = document.getElementById('explosionSound');
    expSound.play();
    spaceObj.isOver = true;
    context.clearRect(0, 0, canvas.width, canvas.height);
    spaceContext.clearRect(0, 0, spaceCanvas.width, spaceCanvas.height);
    
    var imgGameOver = new Image();
    imgGameOver.onload = function() {
        spaceContext.drawImage(imgGameOver,450, 150, 400, 300 );
    };
    imgGameOver.src = 'Images/500.jpg'; 
        
}

function drawScore(){
    context.clearRect(0,0,1240,60);
    context.font= "normal 20px Arial";
    context.strokeStyle = "white";
    context.strokeText("Score:"+score, 40, 50);
}

